<template>
  <!-- MemberApplyFormAudit 入会资料审核 -->
  <PageContainer>
    <view class="container">
      <Tabs v-model="currentTab">
        <Header title="入会资料审核" :default-slot-content-height="78">
          <TabNav tabBarColor="#D7B87C" />
        </Header>
        <template v-for="v in formStageList" :key="v.id">
          <TabsItem :name="v.name" :value="v.id">
            <ApplyForm
              :form-group-list="v.formGroupList"
              :form-item-map="v.formItemVoMap"
              :answer-list="v.customFormUserAnswerList"
              :disabled="true"
              @on-load="formOnload"
            />
          </TabsItem>
        </template>
      </Tabs>
      <!-- 管理员操作 -->
      <view v-if="!loading" class="review-operation">
        <BasicsForm disabled :btn-group-options="{}" @register="formRegister">
          <template #dynamicSlot="{ model, field }">
            <OfficialAccount share-type="View" padding="0px" />
          </template>
        </BasicsForm>
      </view>

      <TButtonGroup v-if="!loading && showBtnGroup">
        <TButton class="gutter-btn" type="warn" text="终止审核" @click="showModal('termination')" />
        <TButton
          class="gutter-btn"
          type="warn"
          text="驳回"
          :icon="'\ueaf2'"
          @click="showModal('reject')"
        />
        <TButton
          class="gutter-btn"
          type="primary"
          text="通过"
          :icon="'\ue60d'"
          @click="showModal('pass')"
        />
      </TButtonGroup>

      <ShowModal
        v-model="modalVisible"
        :title="modalTitle"
        content-width="100%"
        :confirm-text="modalConfirmText"
        :confirm-color="modalConfirmColor"
        @confirm="onSubmit"
      >
        <template #content>
          <view class="pa-20" style="width: 100%">
            <view v-if="modalTips" class="pb-16 fz-14" style="color: #999996">{{ modalTips }}</view>
            <view style="background-color: #f2f3f5">
              <UniEasyinput v-model="remark" type="textarea" placeholder="请输入审核说明" />
            </view>
          </view>
        </template>
      </ShowModal>
      <AuditedReminder v-if="!loading && !showBtnGroup" @back="reLaunch({ name: 'memberAudit' })" />
      <FullLoading :full-loading="loading" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  MemberApplyFormAudit  入会资料审核 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { memberApplyFormDetails, memberApplyFormReview } from '@/api/admin';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, onLoad, redirectTo, reLaunch } from '@/router';
  import { computed, nextTick, ref, unref, watch } from 'vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import type { MemberApplyFormDetailsResult } from '@/api/admin/types';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import {
    ApplyTypeEnum,
    IsFinishEnum,
    MemberApplyFormReviewStatusEnum,
  } from '@/enums/membershipEnum';
  import { Toast } from '@/utils';
  import FullLoading from '@/components/FullLoading/index.vue';
  import type { MemberApplyFormAudit } from '@/router/types/modules';
  import OfficialAccount from '@/components/OfficialAccount/index.vue';
  import { onShareAppMessage } from '@dcloudio/uni-app';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { useForm } from '@/components/Form';
  import ApplyForm from '../components/applyForm.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import ShowModal from '@/components/ShowModal/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import AuditedReminder from '../components/AuditedReminder.vue';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const { hasShareImgConfig } = useAppStoreWithOut();
  const { setWxSharePath } = useAppShare();

  let refresh: MemberApplyFormAudit['refresh'];
  const loading = ref(true);
  const currentTab = ref<number>(Infinity);
  const id = ref<number>();
  const formStageList = ref<MemberApplyFormDetailsResult['memberCustomFormStageVoList']>([]);
  const formStageId = ref<number>();
  const companyName = ref<string>();
  const companyId = ref<number>();
  const levelId = ref<number>();
  const levelName = ref<string>();
  const applyType = ref<ApplyTypeEnum>();
  const isFinish = ref<IsFinishEnum>();
  const statusLocaldata = ref([
    {
      value: MemberApplyFormReviewStatusEnum.AUDITED,
      text: '通过',
    },
    {
      value: MemberApplyFormReviewStatusEnum.REFUSAL,
      text: '驳回',
    },
    {
      value: MemberApplyFormReviewStatusEnum.TERMINATION,
      text: '终止审核',
    },
  ]);

  const getItemIndex = computed(() =>
    unref(formStageList).findIndex((v) => v.id === unref(currentTab)),
  );

  const isAuditFormOnload = ref(false);

  const [register, { appendSchemaByField }] = useForm({
    schemas: [
      {
        field: 'managerhandle',
        label: '管理员操作',
        component: 'Divider',
      },
      {
        field: 'companyName',
        label: '会员名称',
        component: 'Input',
        dynamicDisabled: true,
        defaultValue: companyName,
      },
      {
        field: 'tianyanchaScore',
        label: '单位综合评分',
        component: 'TianyanchaScore',
        defaultValue: companyId,
      },
      {
        field: 'policyService',
        label: '单位政策服务',
        component: 'PolicyService',
        defaultValue: companyName,
      },
      {
        field: 'dSlot',
        label: '',
        labelWidth: '0px',
        component: 'Input',
        slot: 'shareView',
      },
    ],
  });

  function formRegister(event: any) {
    register(event);
    isAuditFormOnload.value = true;
    setAuditFormItemVal();
  }

  watch(currentTab, setAuditFormItemVal);

  const showBtnGroup = ref(false);
  function setAuditFormItemVal() {
    if (!unref(isAuditFormOnload)) return;
    const item = unref(formStageList)[unref(getItemIndex)];
    if (item && item.auditStatus) {
      appendSchemaByField(
        {
          field: 'status',
          label: '入会审核',
          component: 'RadioGroup',
          defaultValue: item?.auditStatus,
          required: true,
          componentProps: {
            localdata: unref(statusLocaldata),
          },
        },
        'policyService',
      );
      appendSchemaByField(
        {
          field: 'remark',
          label: '备注',
          component: 'InputTextArea',
          defaultValue: item?.remark,
          itemProps: {
            labelPosition: 'top',
          },
        },
        'status',
      );
    }

    if (item) {
      showBtnGroup.value = Number(item.id) === currentTab.value && !item.auditStatus;
    }
  }

  const modalVisible = ref(false);
  const modalTitle = ref('');
  const modalConfirmText = ref('');
  const modalConfirmColor = ref('');
  const modalTips = ref('');
  const status = ref<MemberApplyFormReviewStatusEnum>(MemberApplyFormReviewStatusEnum.AUDITED);
  const remark = ref('');
  function showModal(type: 'pass' | 'reject' | 'termination') {
    modalTips.value = '';
    if (type === 'pass') {
      modalTitle.value = '确定资料无误，审核通过？';
      modalConfirmText.value = '审核通过';
      modalConfirmColor.value = '#2878FF';
      status.value = MemberApplyFormReviewStatusEnum.AUDITED;
    }
    if (type === 'reject') {
      modalTitle.value = '确定要驳回申请？';
      modalConfirmText.value = '驳回申请';
      modalConfirmColor.value = '#EA5E0E';
      status.value = MemberApplyFormReviewStatusEnum.REFUSAL;
    }

    if (type === 'termination') {
      modalTitle.value = '确定要终止审核？';
      modalConfirmText.value = '终止审核';
      modalConfirmColor.value = '#EA5E0E';
      modalTips.value = '终止审核之后，将中断取消本次申请流程，对方需要重新发起申请。';
      status.value = MemberApplyFormReviewStatusEnum.TERMINATION;
    }

    modalVisible.value = true;
  }

  async function getDetailsData() {
    if (!id.value) return;
    let r = await memberApplyFormDetails(id.value);
    const list = r.memberCustomFormStageVoList;
    formStageList.value = list;
    companyName.value = r.proposer;
    companyId.value = r.companyId;
    levelId.value = r.levelId;
    levelName.value = r.levelName;
    applyType.value = r.applyType;
    isFinish.value = r.isFinish;

    nextTick(() => {
      currentTab.value = r.formStageId;
      formStageId.value = r.formStageId;
    });
  }

  function onSubmit() {
    id.value &&
      memberApplyFormReview({
        id: id.value,
        status: unref(status),
        remark: unref(remark),
      })
        .then(async (r) => {
          Toast({
            title: '审核成功',
            mask: true,
            success: () => {
              if (
                r.isFinish === IsFinishEnum.DONE &&
                status.value == MemberApplyFormReviewStatusEnum.AUDITED
              ) {
                refresh?.();
                redirectTo({
                  name: 'duesSet',
                  options: {
                    id: id.value as number,
                    memberName: companyName.value,
                    levelName: levelName.value,
                    levelId: levelId.value,
                    applyType: applyType.value,
                  },
                });
              } else {
                refresh?.();
                navigateBack();
              }
            },
          });
        })
        .finally(() => (remark.value = ''));
  }

  const formOnloadCount = ref(0);
  function formOnload() {
    console.log('Form onLoad');
    formOnloadCount.value++;
    if (formOnloadCount.value === formStageList.value.length) {
      loading.value = false;
    }
  }

  onShareAppMessage(() => {
    const tencentCode = hasShareImgConfig(ShareTypeEnum.tencentCode);
    return {
      path: setWxSharePath({ name: 'tencentCode' }),
      imageUrl: tencentCode?.iconUrl,
      title: tencentCode?.desc,
    };
  });

  onLoad<'MemberApplyFormAudit'>((op) => {
    id.value = op.id;
    refresh = op.refresh;
    getDetailsData();
  });
</script>

<style lang="scss" scoped>
  .container {
    width: 100vw;
    min-height: 100vh;
  }
</style>
